/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package MainPack;

/**
 *
 * @author Khoa
 */
import EntityGameObject.PlayPet;
import MainPack.MainMIDlet;
import MaterialPack.Button;
import MaterialPack.ContextDialog;
import MaterialPack.InfoBar;
import Supporter.GlobalVariables;
import Supporter.ImageSupporter;
import java.io.IOException;
import java.io.InputStream;
import javax.microedition.lcdui.*;
import javax.microedition.lcdui.game.*;
import javax.microedition.media.Manager;
import javax.microedition.media.MediaException;
import javax.microedition.media.Player;
import manager.*;

public class GameCanvasView extends GameCanvas {

    private GameThread gameThread;
    private GameLayerManager layerManager;
    private MainMIDlet midlet;
    private Image mosquito;
    private Image bee;
    private Image pet;
    private Image tongueBody;
    private Image petNormal;
    private Image background;
    private Image instructionsImage;
    private Image pausedImage;
    private Image gameOverImage;
    private int gameTicks;
    private boolean initialised;
    private boolean firstLoad;
    private boolean paused;
    private boolean gameOver;
    private int cornerX;
    private int cornerY;
    private int displayWidth;
    private int displayHeight;
    private int offsetx;
    private int offsety;
    private boolean isCollision;
    private int timeCollision;
    private Command exitCmd = new Command("Exit", Command.EXIT, 0);
    private Command playCmd = new Command("Play", Command.SCREEN, 0);
    private Command pauseCmd = new Command("Pause", Command.SCREEN, 0);
    private static String GAME_BACKGROUND = "game/background.jpg";
    private static String GAME_MOS = "game/insect.png";
    private static String GAME_BEE = "game/bee.png";
    private static String FRAMEWORK_INSTRUCTIONS = "framework/instructions.jpg";
    private static String FRAMEWORK_PAUSED = "framework/paused.jpg";
    private static String FRAMEWORK_GAMEOVER = "framework/gameover.jpg";
    private static String GAME_PET = "game/pethead.png";
    private static String GAME_TONGUEBODY = "game/tonguebody.png";
    private static String GAME_PETNORMAL = "game/petnormal.png";
    InfoBar EXPbar = null;
    Player firePlayer;
    ContextDialog[] AdvBubbles = null;
    ContextDialog[] DisBubbles = null;
    ContextDialog[] ExcBubbles = null;
    int AdvBub = 0;
    int DisBub = 0;
    int ExcBub = 0;
    int initvalue;
    
    Button PauseBtn = null;
    
    public GameCanvasView(Player ss) {
        super(false);
        this.setFullScreenMode(true);
        firePlayer = ss;
        PrepareBubble();
        
        Image temp = new ImageSupporter().getImage("/Return.png");
        PauseBtn = new Button(temp, null, getWidth()/ 16, 9*getHeight() / 10, getWidth()/ 8, getHeight() / 10);
    }

    public void GenerateBubble(String text, int wid, int hei, int cooldown, int type) {
        switch (type) {

            case 1:
                DisBubbles[DisBub].SetAnchor(ContextDialog.HORIZON_LEFT, ContextDialog.VERTICAL_TOP);
                DisBubbles[DisBub].Show(text, GlobalVariables.myRandom.nextInt() % (getWidth() / 4) + getWidth() / 2, 250, wid, hei, cooldown, 1);
                if (DisBub < DisBubbles.length - 1) {
                    DisBub++;
                }
                break;
            case 2:
                ExcBubbles[ExcBub].SetAnchor(ContextDialog.HORIZON_MIDDLE, ContextDialog.VERTICAL_MIDDLE);
                ExcBubbles[ExcBub].Show(text, GlobalVariables.myRandom.nextInt() % (getWidth() / 4) + getWidth() / 2, 250, wid, hei, cooldown, 1);
                if (ExcBub < ExcBubbles.length - 1) {
                    ExcBub++;
                }
                break;
        }

    }

    public void PrepareBubble() {
        ImageSupporter imSpp = new ImageSupporter();
        AdvBubbles = new ContextDialog[10];
        Image temp = ImageSupporter.transparent(imSpp.getImage("/Bubble.png"));
        for (int i = 0; i < AdvBubbles.length; i++) {
            AdvBubbles[i] = new ContextDialog(temp);
        }
        AdvBub = 0;

        DisBubbles = new ContextDialog[5];
        temp = ImageSupporter.transparent(imSpp.getImage("/WarningBubble.png"));
        for (int i = 0; i < DisBubbles.length; i++) {
            DisBubbles[i] = new ContextDialog(temp);
        }
        DisBub = 0;

        ExcBubbles = new ContextDialog[5];
        temp = ImageSupporter.transparent(imSpp.getImage("/ExcilentBubble.png"));
        for (int i = 0; i < ExcBubbles.length; i++) {
            ExcBubbles[i] = new ContextDialog(temp);
        }
        ExcBub = 0;
    }

    public void createCanvas(MainMIDlet midlet) throws IOException, MediaException {
        LoadResource();
        this.gameTicks = 900;
        initvalue = this.gameTicks;
        this.initialised = false;
        this.paused = true;
        this.firstLoad = true;
        this.gameOver = false;

        this.midlet = midlet;

        this.gameThread = new GameThread();
        short fps = 0;
        short pps = 0;
        this.isCollision = false;
        this.timeCollision = 0;
    }

    private void LoadResource() throws IOException, MediaException {

        //player.start();
        this.background = ImageSupporter.scaleImage(loadImage(GAME_BACKGROUND), this.getWidth(), this.getHeight());
        this.mosquito = loadImage(GAME_MOS);
        this.bee = loadImage(GAME_BEE);
        this.pet = loadImage(GAME_PET);
        this.tongueBody = loadImage(GAME_TONGUEBODY);
        this.petNormal = loadImage(GAME_PETNORMAL);
        this.pausedImage = loadImage(FRAMEWORK_PAUSED);
        this.gameOverImage = loadImage(FRAMEWORK_GAMEOVER);
        this.instructionsImage = loadImage(FRAMEWORK_INSTRUCTIONS);
        EXPbar = new InfoBar("/option-staminabar.png", "/option-staminabar-mask.png", InfoBar.HORIZON, 100, 40, 20, 127, 15);

    }

    private void checkKeys() {
        if (!gameOver) {
            playGame();
        }
    }

    private Image loadImage(String image) {
        Image splashImage = null;
        try {
            splashImage = Image.createImage("/" + image);
        } catch (Exception e) {
            System.out.println("Couldn't load image " + image);
        }
        return splashImage;
    }

    public void pointerPressed(int x, int y) {
        offsetx = x;
        offsety = y;
        try {
            if (GlobalVariables.sound) {
                firePlayer.stop();
                firePlayer.setLoopCount(1);
                firePlayer.start();
            }
        } catch (MediaException ex) {
            ex.printStackTrace();
        }

        if (this.paused != false) {
            playGame();
        }
//        if (layerManager.checkinsect(offsetx, offsety))
//        {
//            isCollision = true;           
//        }
        if (layerManager.isIsTongueActive() == false && y < 250) {

            layerManager.setPetRotation(x, y);

            int sizePet = layerManager.getPet().getWidth() / 3;
            int xPet = layerManager.getPet().getRefPixelX() + PlayPet.WIDTH / 2 - sizePet;
            int yPet = layerManager.getPet().getRefPixelY() + PlayPet.HEIGHT / 4;

            //ax + by = c
            int a = yPet - offsety;
            int b = offsetx - xPet;
            int c = (a * xPet) + (b * yPet);

            int yRef = yPet;
            int xRef = (c - (b * yRef)) / a;
            layerManager.getTongue(0).setPosition(xRef, yRef);

            int daux, dauy;
            if (xRef < x) {
                daux = 1;
            } else {
                daux = -1;
            }
            if (yRef < y) {
                dauy = 1;
            } else {
                dauy = -1;
            }
            //  int space = layerManager.getPet().getSpeed();
            int space = 2;
            for (int i = 1; i < layerManager.getTongue().length; i++) {
                yRef = layerManager.getTongue(i - 1).getRefPixelY() + dauy * space;
                xRef = (c - (b * yRef)) / a;
                if (Math.abs(layerManager.getTongue(i - 1).getRefPixelX() - xRef) > 4) {
                    xRef = layerManager.getTongue(i - 1).getRefPixelX() + daux * space;
                    layerManager.getTongue(i).setPosition(xRef, (c - (a * xRef)) / b);
                } else {
                    layerManager.getTongue(i).setPosition(xRef, yRef);
                    yRef = yRef + dauy * space;
                }
            }
            layerManager.setIsTongueActive(true);
        }
        PauseBtn.Press(x, y);
    }
    protected void pointerReleased(int x, int y) {
        PauseBtn.Release(x, y);
    }

    protected void updateGame() {

        gameTicks--;
        gameTicks = layerManager.updateLayers(gameTicks);
        if (gameTicks <= 0) {
            gameOver = true;
            gameThread.requestStop();
//            midlet.gameOver();
        }
        UpdateDisBubble();
        UpdateEcxBubble();
        Graphics g = getGraphics();
        paint(g);
        flushGraphics();

        synchronized (this) {
            try {
                wait(15);
            } catch (Exception e) {
            }
        }
    }

    public void UpdateDisBubble() {
        if (DisBubbles != null) {
            for (int i = 0; i < DisBub; i++) {
                if (DisBubbles[i].MyUpdate()) {
                    ContextDialog temp = DisBubbles[i];
                    temp.setIsVisible(false);
                    DisBubbles[i] = DisBubbles[DisBub - 1];
                    DisBubbles[DisBub - 1] = temp;
                    DisBub--;
                }
            }
        }
    }

    public void UpdateEcxBubble() {
        if (ExcBubbles != null) {
            for (int i = 0; i < ExcBub; i++) {
                if (ExcBubbles[i].MyUpdate()) {
                    ContextDialog temp = ExcBubbles[i];
                    temp.setIsVisible(false);
                    ExcBubbles[i] = ExcBubbles[ExcBub - 1];
                    ExcBubbles[ExcBub - 1] = temp;
                    ExcBub--;
                }
            }
        }
    }

    public void paint(Graphics g) {
        if (!initialised) {
            cornerX = g.getClipX();
            cornerY = g.getClipY();
            displayWidth = g.getClipWidth();
            displayHeight = g.getClipHeight();
            layerManager = new GameLayerManager(cornerX, cornerY, displayWidth, displayHeight, mosquito, bee, pet, tongueBody, petNormal, midlet.getPet().getSpeech(), midlet.getPet().getStamina(), midlet.getPet().getTongueLen(), midlet.getPet().getLevel());
            initialised = true;
            gameTicks = layerManager.getPet().getStamina() * 100;
            initvalue = gameTicks;
        }
        g.drawImage(background, 0, 0, Graphics.LEFT | Graphics.TOP);
        EXPbar.setRatio(gameTicks * 100 / initvalue);
        EXPbar.paint(g);

        try {
            layerManager.paint(g);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (DisBubbles != null) {
            for (int i = 0; i < DisBub; i++) {
                DisBubbles[i].paint(g);
            }
        }
        if (ExcBubbles != null) {
            for (int i = 0; i < ExcBub; i++) {
                ExcBubbles[i].paint(g);
            }
        }
        g.drawString(String.valueOf(gameTicks / 10), 60, 17, Graphics.TOP | Graphics.LEFT);
        int temp = layerManager.GetScoreInsect();
        if (temp != -1) {

            if (temp < 0) {
                GenerateBubble(String.valueOf(temp), 40, 40, 30, 1);

            } else {
                GenerateBubble("+" + String.valueOf(temp), 40, 40, 30, 2);

            }
        }
        if (firstLoad) {
            firstLoad = false;
            drawGreyOut(g);
            g.drawImage(instructionsImage, displayWidth / 2, displayHeight / 2,
                    Graphics.HCENTER | Graphics.VCENTER);
        } else if (paused) {
            drawGreyOut(g);
            g.drawImage(pausedImage, displayWidth / 2, displayHeight / 2,
                    Graphics.HCENTER | Graphics.VCENTER);
        } else if (gameOver) {
            drawGreyOut(g);
            g.drawImage(gameOverImage, displayWidth / 2, displayHeight / 2,
                    Graphics.HCENTER | Graphics.VCENTER);
            ResultCanvas.TotalInsect = layerManager.getNoOfInsect();
//                ResultCanvas.MoneyGet=layerManager.getMoney()*100;
//                ResultCanvas.Score = layerManager.getScore()*2;
            try {
                midlet.SwitchTo(MainMIDlet.SCENE_RESULT);
            } catch (IOException ex) {
                ex.printStackTrace();
            } catch (MediaException ex) {
                ex.printStackTrace();
            }


        }
         PauseBtn.paint(g);

    }

    private void drawGreyOut(Graphics g) {
        int[] buf = new int[displayWidth];
        for (int i = 0; i < displayWidth; i++) {
            buf[i] = 0x88ffffff;
        }
        g.drawRGB(buf, 0, 0, cornerX, cornerY, displayWidth, displayHeight,
                true);
    }

    public void stopGame() {
        this.gameThread.requestStop();
    }

    public void playGame() {
        this.paused = false;
        this.gameThread.requestPlay();
    }

    public void pauseGame() {
        this.paused = true;
        updateGame();
        this.gameThread.requestPause();
    }

    public void reset() throws IOException, MediaException {
        this.gameThread = null;
        this.createCanvas(midlet);
        //updateGame();
        this.paused = false;
    }

    class GameThread extends Thread {

        private boolean pause = true;
        private boolean stop = false;
        private boolean started = false;

        public void requestPlay() {
            this.pause = false;
            if (!started) {
                this.start();
                this.started = true;
            }
        }

        public void requestPause() {
            this.pause = true;
        }

        public void requestStop() {
            this.stop = true;
        }

        public void run() {
            while (!stop) {
                if (!pause) {
                    //  checkKeys();
                    updateGame();
                }
            }
        }
    }
}
